<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>
        <input type="file" id="file1">
        <div id="preview"></div>
        <button id="upload">上传</button>
    </p>
</body>
<script>
    // 获取原生
    const upload = document.querySelector('#upload');
    const file1 = document.querySelector('#file1');
    const preview = document.querySelector('#preview');

    upload.onclick = function() {
        if (file1.files.length === 0) return alert('请选择文件');
        let fd = new FormData();
        fd.append('avatar', file1.files[0]);
        
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://www.liulongbin.top:3006/api/upload/avatar');
        xhr.send(fd);
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let res = JSON.parse(xhr.responseText);
                if (res.status !== 200) return alert(res.msg);
                preview.innerHTML = `<img src="http://www.liulongbin.top:3006${res.url}" />`;
            }
        }
    }
</script>
</html>